package com.secsbrain.development.web.ws.base;

import com.secsbrain.development.web.dto.UserInfoDTO;
import com.secsbrain.sso.core.SsoHelper;
import com.secsbrain.sso.model.dto.system.UserDetailDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.io.IOException;

/**
 * Created by yangyang.zhang on 2017/7/20.
 */
public abstract class BaseHandler extends TextWebSocketHandler implements WebSocketConfigurer {
    protected static final Logger LOGGER = LoggerFactory.getLogger(BaseHandler.class);

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        auth(session);
    }

    protected void auth(WebSocketSession session) throws IOException, InterruptedException {
        LOGGER.info("[WebLogHandler:onOpen] new session open,sessionId:[{}]", session.getId());
        UserInfoDTO userInfo = null;
        UserDetailDTO userDetailDTO= SsoHelper.currentUser();
        if(userDetailDTO!=null){
        	userInfo=new UserInfoDTO();
        	userInfo.setId(userDetailDTO.getId());
        	userInfo.setName(userDetailDTO.getRealName());
        }
      
        if (userInfo != null) {
            LOGGER.info("[WebLogHandler:onOpen] new session auth success,sessionId:[{}],userId:[{}],username:[{}]", session.getId(), userInfo.getId(), userInfo.getName());
            session.sendMessage(new TextMessage("建立连接成功！" + System.lineSeparator()));
            return;
        }
        LOGGER.info("[WebLogHandler:onOpen] new session auth failure,sessionId:[{}]", session.getId());
        session.close();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(this, getPaths())
                .addInterceptors(getHandshakeInterceptors())
                .setAllowedOrigins(getAllowedOrigins());
    }

    @Override
    public abstract void handleTextMessage(WebSocketSession session, TextMessage message);

    public abstract String[] getPaths();

    public HandshakeInterceptor[] getHandshakeInterceptors() {
        return new HandshakeInterceptor[]{new HttpSessionHandshakeInterceptor()};
    }

    public String[] getAllowedOrigins() {
        return new String[]{"*"};
    }

}
